package io.iec.edp.caf.core.session.service.Impl;

import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.core.session.CafSession;
import io.iec.edp.caf.core.session.CafSessionContextHolder;
import io.iec.edp.caf.core.session.ICafSessionService;
import io.iec.edp.caf.core.session.service.CafSessionService;
import io.iec.edp.caf.i18n.api.LanguageService;
import lombok.extern.slf4j.Slf4j;

/**
 * CafSessionService工具类实现
 *
 * @author manwenxing01
 * @date 2023-04-27 15:20
 */
@Slf4j
public class CafSessionServiceHelper implements CafSessionService {

    @Override
    public boolean setLanguage(String languageCode) {
        try {
            LanguageService languageService = SpringBeanUtils.getBean(LanguageService.class);
            boolean match = languageService.getEnabledLanguages().stream().anyMatch(lang -> lang.getCode().equals(languageCode));

            if (match) {
                CafSession session = CafSessionContextHolder.getCurrentSession();
                session.setLanguage(languageCode);
                //重新设置session信息
                CafSessionContextHolder.setCurrentSession(session);

                //更新
                ICafSessionService sessionService = SpringBeanUtils.getBean(ICafSessionService.class);
                sessionService.update(session);

                return true;
            }

            return false;
        } catch (Exception e) {
            return false;
        }
    }

}
